package net.maku.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.framework.security.user.SecurityUser;
import net.maku.module.convert.AgCategoryConvert;
import net.maku.module.dao.AgCategoryDao;
import net.maku.module.dao.AgCategoryPermissionDao;
import net.maku.module.dao.AgContentDao;
import net.maku.module.entity.*;
import net.maku.module.query.AgCategoryQuery;
import net.maku.module.service.AgApproveService;
import net.maku.module.service.AgCategoryPermissionService;
import net.maku.module.service.AgCategoryService;
import net.maku.module.service.AgContentService;
import net.maku.module.util.UrlReplaceUtil;
import net.maku.module.vo.AgCategoryVO;
import net.maku.module.vo.AgContentCombined;
import net.maku.system.dao.SysUserDao;
import net.maku.system.dao.SysUserRoleDao;
import net.maku.system.entity.SysUserEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
@AllArgsConstructor
public class AgCategoryServiceImpl extends BaseServiceImpl<AgCategoryDao, AgCategoryEntity> implements AgCategoryService {

    @Autowired
    private AgCategoryDao agCategoryDao;
    @Autowired
    private AgContentDao agContentDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Resource
    private AgCategoryPermissionDao agCategoryPermissionDao;


    private final AgApproveService agApproveService;

    @Autowired
    private UrlReplaceUtil urlReplaceUtil;


    public PageResult<AgCategoryVO> getCategoryList(AgCategoryQuery query) {

        IPage<AgCategoryEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        return new PageResult<>(AgCategoryConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    @Override
    public Result<PageResult<AgCategoryVO>> getCategoryListByUser(Integer websiteId,
                                                                  long userId,
                                                                  Integer pageNum,
                                                                  Integer pageSize,
                                                                  String approveState) {
        System.out.println("========== [DEBUG] 调试开始 getCategoryListByUser ==========");
        System.out.println("[DEBUG] websiteId=" + websiteId + ", userId=" + userId + ", approveState=" + approveState);

        List<String> roleNames = sysUserRoleDao.getRoleInfoList(userId);
        System.out.println("[DEBUG] 当前用户角色: " + roleNames);

        List<Long> categoryIds = agCategoryPermissionDao.getCategoryIdsByUserId(userId);
        System.out.println("[DEBUG] 用户可访问的栏目ID: " + categoryIds);

        LambdaQueryWrapper<AgCategoryEntity> lambdaQueryWrapper = new LambdaQueryWrapper<AgCategoryEntity>()
                .eq(AgCategoryEntity::getWebsiteId, websiteId)
                .eq(AgCategoryEntity::getDeleted, 0);

        if (categoryIds.size() <= 0 && !roleNames.contains("admin")) {
            System.out.println("[DEBUG] 用户没有数据权限，返回空");
            return Result.ok(new PageResult<>(Collections.emptyList(), 0L));
        }

        if (!roleNames.contains("admin")) {
            lambdaQueryWrapper = lambdaQueryWrapper.in(AgCategoryEntity::getId, categoryIds);
        }

        // ========== 审批状态逻辑 ==========
        if (!StringUtils.isEmpty(approveState)) {
            System.out.println("[DEBUG] 进入审批状态逻辑分支 approveState=" + approveState);

            Map<String, Object> param1 = new HashMap<>();
            param1.put("businessType", "1");
            param1.put("approveState", approveState);
            param1.put("userId", userId);
            if ("4".equals(approveState)) {
                param1.put("updater", userId);
            }

            List<AgApproveEntity> data3 = agApproveService.queryList(param1);
            System.out.println("[DEBUG] 审批记录条数：" + (data3 == null ? 0 : data3.size()));

            if (CollectionUtils.isEmpty(data3)) {
                System.out.println("[DEBUG] 没有审批数据，返回空");
                return Result.ok(new PageResult<>(Collections.emptyList(), 0L));
            }

            List<Integer> result = data3.stream()
                    .map(AgApproveEntity::getBusinessId)
                    .collect(Collectors.toList());

            lambdaQueryWrapper = lambdaQueryWrapper.in(AgCategoryEntity::getId, result);
            lambdaQueryWrapper.orderByAsc(AgCategoryEntity::getSort);

            List<AgCategoryEntity> categories = baseMapper.selectList(lambdaQueryWrapper);
            System.out.println("[DEBUG] 审批逻辑查到栏目数量：" + categories.size());

            if ("4".equals(approveState)) {
                categories = new ArrayList<>();
                for (AgApproveEntity approve : data3) {
                    AgCategoryEntity agCategoryEntity = baseMapper.selectById(approve.getBusinessId());
                    if (agCategoryEntity != null) {
                        agCategoryEntity.setAgApprove(approve);
                        categories.add(agCategoryEntity);
                    }
                }
            }

            List<AgCategoryVO> resultList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(categories)) {
                for (AgCategoryEntity category : categories) {
                    AgCategoryVO vo = new AgCategoryVO();
                    BeanUtils.copyProperties(category, vo);
                    vo.setChildren(null);

                    // --- 调试：打印栏目基础信息
                    System.out.println("[DEBUG] 栏目ID=" + category.getId() + ", 栏目名称=" + category.getName());

                    // --- 调试：尝试查询内容模板类型
                    AgContent content = agContentDao.selectOne(
                            new LambdaQueryWrapper<AgContent>()
                                    .eq(AgContent::getCategoryId, category.getId())
                                    .last("LIMIT 1")
                    );
                    if (content != null) {
                        vo.setTemplateType(content.getTemplateType());
                        System.out.println("[DEBUG] => 找到内容，categoryId=" + category.getId() +
                                ", templateType=" + content.getTemplateType());
                    } else {
                        System.out.println("[DEBUG] => 没有对应内容记录 categoryId=" + category.getId());
                    }

                    // --- 审批信息
                    if (vo.getAgApprove() == null) {
                        Map<String, Object> param2 = new HashMap<>();
                        param2.put("businessType", "1");
                        param2.put("businessId", vo.getId());
                        param2.put("approveState", "2");
                        param2.put("userId", userId);
                        List<AgApproveEntity> data4 = agApproveService.queryList(param2);
                        vo.setAgApprove(CollectionUtils.isEmpty(data4) ? null : data4.get(0));
                    }

                    // --- 父级栏目
                    List<AgCategoryEntity> res = new ArrayList<>();
                    getParentList(category.getParentId(), res);
                    if (category.getParentId() != 0 && !CollectionUtils.isEmpty(res) && res.get(0) != null) {
                        String parentNames = res.stream()
                                .map(AgCategoryEntity::getName)
                                .collect(Collectors.joining("/"));
                        vo.setParentName(parentNames);
                        vo.setTopId(String.valueOf(res.get(res.size() - 1).getId()));
                        vo.setTopName(res.get(res.size() - 1).getName());
                    }

                    resultList.add(vo);
                }
            }

            System.out.println("========== [DEBUG] 审批逻辑结束 ==========");
            return getPageInfo(resultList, pageNum, pageSize);
        }

        // ========== 普通查询逻辑 ==========
        lambdaQueryWrapper.orderByAsc(AgCategoryEntity::getSort);
        List<AgCategoryEntity> categories = baseMapper.selectList(lambdaQueryWrapper);
        System.out.println("[DEBUG] 普通查询栏目数量：" + (categories == null ? 0 : categories.size()));

        List<AgCategoryVO> allCategories = convertToHierarchyNew(categories, userId);

        for (AgCategoryVO vo : allCategories) {
            AgContent content = agContentDao.selectOne(
                    new LambdaQueryWrapper<AgContent>()
                            .eq(AgContent::getCategoryId, vo.getId())
                            .last("LIMIT 1")
            );
            if (content != null) {
                vo.setTemplateType(content.getTemplateType());
                System.out.println("[DEBUG] => categoryId=" + vo.getId() +
                        ", templateType=" + content.getTemplateType());
            } else {
                System.out.println("[DEBUG] => categoryId=" + vo.getId() + " 没有对应内容记录");
            }
        }

        System.out.println("========== [DEBUG] 普通逻辑结束 ==========");
        return getPageInfo(allCategories, pageNum, pageSize);
    }




    public List<AgCategoryEntity> getParentList(Integer parentId, List<AgCategoryEntity> res) {

        AgCategoryEntity agCategoryEntity = agCategoryDao.selectById(parentId);
        res.add(agCategoryEntity);
        if (null != agCategoryEntity) {
            if (0 == agCategoryEntity.getParentId()) {
                return res;
            }
            return getParentList(agCategoryEntity.getParentId(), res);
        }
        return new ArrayList<>();


    }

    private Result<PageResult<AgCategoryVO>> getPageInfo(List<AgCategoryVO> allCategories,
                                                         Integer pageNum,
                                                         Integer pageSize) {
        int total = allCategories.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        if (fromIndex >= total) {
            return Result.ok(new PageResult<>(Collections.emptyList(), (long) total));
        }

        allCategories.sort(Comparator.comparingInt(AgCategoryVO::getSort));
        List<AgCategoryVO> paginatedCategories = allCategories.subList(fromIndex, toIndex);

        // ✅ 递归补充模板类型（每个栏目含children都处理）
        for (AgCategoryVO category : paginatedCategories) {
            fillTemplateTypeRecursively(category);
        }

        return Result.ok(new PageResult<>(paginatedCategories, (long) total));
    }

    /**
     * 递归查询每个栏目对应的第一个内容的模板类型
     */
    private void fillTemplateTypeRecursively(AgCategoryVO categoryVO) {
        if (categoryVO == null || categoryVO.getId() == null) return;

        // 查这个栏目是否有内容
        Integer templateType = agContentDao.getFirstTemplateTypeByCategoryId(categoryVO.getId());
        if (templateType != null) {
            categoryVO.setTemplateType(templateType);
        }

        // 递归对子栏目执行同样操作
        if (!CollectionUtils.isEmpty(categoryVO.getChildren())) {
            for (AgCategoryVO child : categoryVO.getChildren()) {
                fillTemplateTypeRecursively(child);
            }
        }
    }


    private LambdaQueryWrapper<AgCategoryEntity> getWrapper(AgCategoryQuery query) {
        LambdaQueryWrapper<AgCategoryEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(query.getStatus() != null, AgCategoryEntity::getStatus, query.getStatus());
        return wrapper;
    }

    @Override
    public void addCategoryList(AgCategoryVO vo) {
        AgCategoryEntity entity = AgCategoryConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void updateCategoryList(AgCategoryVO vo) {
        AgCategoryEntity entity = AgCategoryConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategoryList(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public Result<PageResult<AgCategoryVO>> getCategoriesByWebsiteId(Integer websiteId,
                                                                     Integer pageNum,
                                                                     Integer pageSize) {
        // 查询所有满足条件的栏目
        List<AgCategoryEntity> categories = baseMapper.selectList(new LambdaQueryWrapper<AgCategoryEntity>()
                .eq(AgCategoryEntity::getWebsiteId, websiteId)
                .eq(AgCategoryEntity::getDeleted, 0)
                .orderByAsc(AgCategoryEntity::getSort)
        );
        // 转换为层级结构
        List<AgCategoryVO> allCategories = convertToHierarchy(categories, null);
        // 进行分页操作
        int total = allCategories.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        // 如果分页起始位置超出总数，返回空数据
        if (fromIndex >= total) {
            return Result.ok(new PageResult<>(Collections.emptyList(), (long) total));
        }
        allCategories.sort(Comparator.comparingInt(AgCategoryVO::getSort));
        // 获取分页后的数据
        List<AgCategoryVO> paginatedCategories = allCategories.subList(fromIndex, toIndex);

        // 返回分页结果
        return Result.ok(new PageResult<>(paginatedCategories, (long) total));
    }

    @Override
    public Result<List<AgCategoryVO>> getCategoriesAll(Integer websiteId) {
        // 查询所有满足条件的栏目
        List<AgCategoryEntity> categories = baseMapper.selectList(new LambdaQueryWrapper<AgCategoryEntity>()
                .eq(AgCategoryEntity::getWebsiteId, websiteId)
                .eq(AgCategoryEntity::getDeleted, 0)
                .orderByAsc(AgCategoryEntity::getSort)
        );

        // 转换为层级结构
        List<AgCategoryVO> allCategories = convertToHierarchy(categories, null);

        // 查询 ag_content 表中每个 category_id 对应的第一个记录的 templateType
        Map<Integer, Integer> categoryToTemplateTypeMap = getCategoryToTemplateTypeMap(
                categories.stream().map(cat -> cat.getId().intValue()).collect(Collectors.toList())
        );

        // 递归填充 templateType
        fillTemplateType(allCategories, categoryToTemplateTypeMap);

        // 排序（如果层级转换后仍需要排序）
        allCategories.sort(Comparator.comparingInt(AgCategoryVO::getSort));

        // 返回全量数据
        return Result.ok(allCategories);
    }

    @Override
    public int updateCategoryImage(Long categoryId, String url) {
        return agCategoryDao.updateCategoryImage(categoryId, url);
    }

    /**
     * 递归填充 templateType
     *
     * @param categories                栏目列表
     * @param categoryToTemplateTypeMap category_id -> templateType 映射
     */
    private void fillTemplateType(List<AgCategoryVO> categories, Map<Integer, Integer> categoryToTemplateTypeMap) {
        for (AgCategoryVO category : categories) {
            // 设置当前节点的 templateType
            Integer templateType = categoryToTemplateTypeMap.get(category.getId().intValue());
            category.setTemplateType(templateType);

            // 递归处理子节点
            if (category.getChildren() != null && !category.getChildren().isEmpty()) {
                fillTemplateType(category.getChildren(), categoryToTemplateTypeMap);
            }
        }
    }

    /**
     * 查询 ag_content 表中每个 category_id 对应的第一个记录的 templateType
     *
     * @param categoryIds 栏目 ID 列表
     * @return category_id -> templateType 的映射
     */
    private Map<Integer, Integer> getCategoryToTemplateTypeMap(List<Integer> categoryIds) {
        if (categoryIds == null || categoryIds.isEmpty()) {
            return Collections.emptyMap();
        }

        List<AgContent> contents = agContentDao.selectFirstByCategoryIds(categoryIds);

        return contents.stream()
                .filter(Objects::nonNull)
                .filter(content -> content.getCategoryId() != null)
                .filter(content -> content.getTemplateType() != null)
                .collect(Collectors.toMap(
                        AgContent::getCategoryId,
                        AgContent::getTemplateType
                ));
    }


    private List<AgCategoryVO> convertToHierarchyNew(List<AgCategoryEntity> categories, Long userId) {


        // 用来存储每个栏目ID对应的VO对象
        Map<Integer, AgCategoryVO> map = new HashMap<>();
        // 存储最顶层的栏目（parentId为0）
        List<AgCategoryVO> result = new ArrayList<>();

        // 将每个category转换为AgCategoryVO并放入map中
        for (AgCategoryEntity category : categories) {
            AgCategoryVO vo = new AgCategoryVO();
            BeanUtils.copyProperties(category, vo);
            vo.setChildren(null); // 确保每个AgCategoryVO没有children字段（默认不显示）
            map.put(category.getId().intValue(), vo);
        }

        // 遍历map，构建层级关系
        for (AgCategoryVO categoryVO : map.values()) {
            // 如果是根栏目（parentId为0），就直接添加到最顶层的列表
            if (categoryVO.getParentId() == null || categoryVO.getParentId() == 0) {
                result.add(categoryVO);
            } else {
                // 否则，找到对应的父级栏目，将当前栏目添加到父级的children中
                AgCategoryVO parent = map.get(categoryVO.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>()); // 如果父节点没有children，初始化为空列表
                    }
                    parent.getChildren().add(categoryVO); // 将子栏目加入父栏目
                }
            }
        }

        // 对父节点下的子节点进行排序
        for (AgCategoryVO parent : result) {
            if (parent.getChildren() != null) {
                parent.getChildren().sort(Comparator.comparingInt(AgCategoryVO::getSort)); // 子节点按sort排序
            }
        }
        for (AgCategoryVO categoryVO : map.values()) {
            if (categoryVO.getUpdater() != null) {
                categoryVO.setModifiedByName(agCategoryDao.getUpdateName(categoryVO.getUpdater()));
            }
            if (categoryVO.getCreator() != null) {
                categoryVO.setCreatedByName(agCategoryDao.getCreateName(categoryVO.getCreator()));
            }
            if (categoryVO.getId() != null && userId != null) {
                //查询这个栏目的所有权限数据
                Map param = new HashMap();
                param.put("categoryId", categoryVO.getId());
                List<AgCategoryPermission> data = agCategoryPermissionDao.queryList(param);
                categoryVO.setAgCategoryPermissions(data);

                //Map param = new HashMap();
                param.put("userId", userId);
                List<AgCategoryPermission> data1 = agCategoryPermissionDao.queryList(param);
                if (!CollectionUtils.isEmpty(data1)) {
                    categoryVO.setAgCategoryPermission(data1.get(0));
                } else {
                    categoryVO.setAgCategoryPermission(null);
                }
                Map param1 = new HashMap();
                param1.put("businessType", "1");
                param1.put("businessId", categoryVO.getId());
                List<AgApproveEntity> data2 = agApproveService.queryList(param1);
                categoryVO.setAgApproveList(data2);

                param1.put("approveState", "2");
                param1.put("userId", userId);
                List<AgApproveEntity> data3 = agApproveService.queryList(param1);

                if (!CollectionUtils.isEmpty(data3)) {
                    categoryVO.setAgApprove(data3.get(0));
                } else {
                    categoryVO.setAgApprove(null);
                }

                //查询模板类型

                Map param2 = new HashMap();
                param2.put("categoryId",categoryVO.getId());
                List<AgContentCombined> linkList = agContentDao.queryList(param2);
                if(!CollectionUtils.isEmpty(linkList)){
                    categoryVO.setTemplateType(linkList.get(0).getTemplateType());

                }

            }


        }
        return result;
    }

    private List<AgCategoryVO> convertToHierarchy(List<AgCategoryEntity> categories, Long userId) {


        // 用来存储每个栏目ID对应的VO对象
        Map<Integer, AgCategoryVO> map = new HashMap<>();
        // 存储最顶层的栏目（parentId为0）
        List<AgCategoryVO> result = new ArrayList<>();

        // 将每个category转换为AgCategoryVO并放入map中
        for (AgCategoryEntity category : categories) {
            AgCategoryVO vo = new AgCategoryVO();
            BeanUtils.copyProperties(category, vo);
            vo.setChildren(null); // 确保每个AgCategoryVO没有children字段（默认不显示）
            map.put(category.getId().intValue(), vo);
        }

        // 遍历map，构建层级关系
        for (AgCategoryVO categoryVO : map.values()) {
            // 如果是根栏目（parentId为0），就直接添加到最顶层的列表
            if (categoryVO.getParentId() == null || categoryVO.getParentId() == 0) {
                result.add(categoryVO);
            } else {
                // 否则，找到对应的父级栏目，将当前栏目添加到父级的children中
                AgCategoryVO parent = map.get(categoryVO.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>()); // 如果父节点没有children，初始化为空列表
                    }
                    parent.getChildren().add(categoryVO); // 将子栏目加入父栏目
                }
            }
        }

        // 对父节点下的子节点进行排序
        for (AgCategoryVO parent : result) {
            if (parent.getChildren() != null) {
                parent.getChildren().sort(Comparator.comparingInt(AgCategoryVO::getSort)); // 子节点按sort排序
            }
        }
        for (AgCategoryVO categoryVO : map.values()) {
            if (categoryVO.getUpdater() != null) {
                categoryVO.setModifiedByName(agCategoryDao.getUpdateName(categoryVO.getUpdater()));
            }
            if (categoryVO.getCreator() != null) {
                categoryVO.setCreatedByName(agCategoryDao.getCreateName(categoryVO.getCreator()));
            }
        }
        return result;
    }

    @Override
    public List<AgCategoryVO> getSubCategories(Integer parentId, Integer type) {
        long start = System.currentTimeMillis();

        // ==============================
        // 1️⃣ 一次性查询所有栏目
        // ==============================
        List<AgCategoryEntity> allCategories = baseMapper.selectList(
                new LambdaQueryWrapper<AgCategoryEntity>()
                        .eq(type == 1, AgCategoryEntity::getStatus, 1)
                        .eq(AgCategoryEntity::getDeleted, 0)
                // 如果系统有 websiteId，可加上：
                //.eq(AgCategoryEntity::getWebsiteId, currentWebsiteId)
        );
        long t1 = System.currentTimeMillis();
        System.out.println("[Perf] Query category cost: " + (t1 - start) + "ms, count=" + allCategories.size());

        if (allCategories.isEmpty()) {
            return Collections.emptyList();
        }

        // ==============================
        // 2️⃣ 获取模板映射（批量查询）
        // ==============================
        List<Integer> allIds = new ArrayList<>(allCategories.size());
        for (AgCategoryEntity c : allCategories) {
            allIds.add(c.getId().intValue());
        }
        Map<Integer, Integer> templateTypeMap = getCategoryToTemplateTypeMap(allIds);
        long t2 = System.currentTimeMillis();
        System.out.println("[Perf] Template map cost: " + (t2 - t1) + "ms");

        // ==============================
        // 3️⃣ 转换为 VO，并放入 Map
        // ==============================
        Map<Long, AgCategoryVO> voMap = new HashMap<>(allCategories.size());
        for (AgCategoryEntity category : allCategories) {
            AgCategoryVO vo = new AgCategoryVO();
            vo.setId(category.getId());
            vo.setParentId(category.getParentId());
            vo.setName(category.getName());
            vo.setDescription(category.getDescription());
            vo.setSort(category.getSort());
            vo.setLevel(category.getLevel());
            vo.setStatus(category.getStatus());
            vo.setCreateTime(category.getCreateTime());
            vo.setUpdateTime(category.getUpdateTime());
            vo.setDeleted(category.getDeleted());
            vo.setCreator(category.getCreator());
            vo.setUpdater(category.getUpdater());
            vo.setVersion(category.getVersion());
            vo.setWebsiteId(category.getWebsiteId());
            vo.setTemplateType(templateTypeMap.get(category.getId().intValue()));
            voMap.put(category.getId(), vo);
        }
        long t3 = System.currentTimeMillis();
        System.out.println("[Perf] Build VO map cost: " + (t3 - t2) + "ms");

        // ==============================
        // 4️⃣ 构建父子关系
        // ==============================
        for (AgCategoryVO vo : voMap.values()) {
            Integer pid = vo.getParentId();
            if (pid == null) continue;
            AgCategoryVO parent = voMap.get(pid);
            if (parent != null) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>(4)); // 初始容量
                }
                parent.getChildren().add(vo);
            }
        }
        long t4 = System.currentTimeMillis();
        System.out.println("[Perf] Build tree cost: " + (t4 - t3) + "ms");

        // ==============================
        // 5️⃣ 获取父栏目名称
        // ==============================
        String parentName = baseMapper.getParentName(parentId);

        // ==============================
        // 6️⃣ 返回指定 parentId 的一级子栏目
        // ==============================
        List<AgCategoryVO> result = new ArrayList<>();
        for (AgCategoryVO vo : voMap.values()) {
            if (Objects.equals(vo.getParentId(), parentId)) {
                vo.setParentName(parentName);
                result.add(vo);
            }
        }

        // 按 sort 排序
        result.sort(Comparator.comparingInt(AgCategoryVO::getSort));

        long end = System.currentTimeMillis();
        System.out.println("[Perf] Total cost: " + (end - start) + "ms");

        return result;
    }


    @Override
    public int addParentCategory(AgCategoryEntity entity) {
        return baseMapper.insert(entity);
    }

    @Override
    public int addChildCategory(AgCategoryEntity entity) {
        //检查父栏目id是否关联了内容，如果关联了直接返回-1，不让新增
        Long count = agContentDao.selectCount(new LambdaQueryWrapper<AgContent>()
                .eq(AgContent::getCategoryId, entity.getParentId())
        );
        if (count > 1) {
            return -1; // 父栏目关联了内容，无法新增子栏目
        }
        // 查询父栏目的 level
        Integer parentLevel = baseMapper.selectOne(new LambdaQueryWrapper<AgCategoryEntity>()
                .select(AgCategoryEntity::getLevel)
                .eq(AgCategoryEntity::getId, entity.getParentId())
        ).getLevel();
        if (parentLevel == null) {
            throw new IllegalArgumentException("父栏目不存在，无法新增子栏目");
        }
        // 设置子栏目的 level
        entity.setLevel(parentLevel != null ? parentLevel + 1 : 1); // 如果 parentLevel 为空，默认设置为 1

        // 设置 deleted 字段
        entity.setDeleted(0);

        entity.setApproveType("1");
        entity.setApproveState("1");
        entity.setCreateTime(new Date());
        // 插入数据
        int insert = baseMapper.insert(entity);
        Long id = entity.getId();
        if (entity.getTemplateType() != null) {
            AgContent agContent = new AgContent();
            agContent.setCategoryId(Math.toIntExact(id));
            agContent.setTemplateType(entity.getTemplateType());
            agContentDao.insert(agContent);
        }

        //初始化权限基础数据
        //继承父级权限
        long executor = SecurityUser.getUser().getId();
        Map param = new HashMap();
        param.put("categoryId", entity.getParentId());
        //param.put("userId", executor);
        List<AgCategoryPermission> agCategoryPermissions = agCategoryPermissionDao.queryList(param);
        if (!CollectionUtils.isEmpty(agCategoryPermissions)) {
            agCategoryPermissions.forEach(e -> {
                if (!"3".equals(e.getColumnPermissions())) {
                    e.setButtonPermissions("1,2,3,4,5,6,7");
                }
                e.setCategoryId(id);
                e.setId(null);
                agCategoryPermissionDao.insert(e);
            });

        }
        //初始化审批流程
        //agApproveService.addApprove("1",id,"1","1");

        return insert;


    }

    @Override
    public int updateParentCategory(Long categoryId, AgCategoryVO categoryVO) {
        AgCategoryEntity entity = baseMapper.selectById(categoryId);
        if (entity == null || entity.getParentId() != 0) {
            return -1; // 无效操作
        }

        entity.setName(categoryVO.getName());
        entity.setSort(categoryVO.getSort());
        entity.setStatus(categoryVO.getStatus());
        entity.setImageUrl(categoryVO.getImageUrl());
        entity.setDescription(categoryVO.getDescription());

        try {
            entity.setApproveState("1");
            entity.setApproveType("2");
            entity.setPublishTime(categoryVO.getPublishTime());
            entity.setRevokeTime(categoryVO.getRevokeTime());
            return baseMapper.updateById(entity);
        } catch (DuplicateKeyException e) {
            if (e.getMessage() != null && e.getMessage().contains("unique_tenant_ag_category")) {
                return -2; // 特殊返回值表示唯一键冲突
            }
            return 0; // 其他数据库错误
        }
    }


    @Override
    public int updateChildCategory(Long categoryId, AgCategoryVO categoryVO) {
        AgCategoryEntity entity = baseMapper.selectById(categoryId);
        if (entity == null || entity.getParentId() == 0) {
            return -1;
        }
        entity.setName(categoryVO.getName());
        entity.setImageUrl(categoryVO.getImageUrl());
        entity.setSort(categoryVO.getSort());
        entity.setDescription(categoryVO.getDescription());
        entity.setStatus(categoryVO.getStatus());
        entity.setApproveState("1");
        entity.setApproveType("2");
        entity.setPublishTime(categoryVO.getPublishTime()==null?"":categoryVO.getPublishTime());
        entity.setRevokeTime(categoryVO.getRevokeTime()==null?"":categoryVO.getPublishTime());
        return baseMapper.updateById(entity);
    }

    @Override
    public int deleteChildCategory(Long categoryId) {
        AgCategoryEntity entity = baseMapper.selectById(categoryId);
        if (entity == null || entity.getParentId() == 0) {
            return -1;
        }
        entity.setApproveState("1");
        entity.setApproveType("3");
        //baseMapper.updateById(entity);
        baseMapper.deleteById(categoryId);
        return 1;
    }

    @Override
    public int deleteParentCategory(Long categoryId) {
        AgCategoryEntity entity = baseMapper.selectById(categoryId);
        if (entity == null || entity.getParentId() != 0) {
            return -1;
        }

        // 检查是否有子栏目
        Long childCount = baseMapper.selectCount(
                new LambdaQueryWrapper<AgCategoryEntity>().eq(AgCategoryEntity::getParentId, categoryId)
        );
        if (childCount > 0) {
            return -2;
        }
        entity.setApproveState("1");
        entity.setApproveType("3");
        //baseMapper.updateById(entity);
        baseMapper.deleteById(categoryId);
        return 1;
    }

    @Override
    public List<AgCategoryVO> getParents(HttpServletRequest request, Integer websiteId) {
        // 1. 查询该网站下的所有栏目
        List<AgCategoryVO> allCategories = agCategoryDao.findAllByWebsiteIdOrderBySortAsc(websiteId);
        if (CollectionUtils.isEmpty(allCategories)) {
            return Collections.emptyList();
        }

        // 使用工具类替换URL
        urlReplaceUtil.replaceImageUrls(request,allCategories);

        // 2. 查询每个栏目对应的第一个内容的 templateType（DAO中用Mapper实现）
        List<CategoryTemplateDTO> templateList = agContentDao.getFirstContentTemplateType();
        // 注意类型统一为 Long
        Map<Long, Integer> templateMap = templateList.stream()
                .collect(Collectors.toMap(
                        dto -> dto.getCategoryId().longValue(),
                        CategoryTemplateDTO::getTemplateType
                ));

        // 3. 使用 Map 缓存 id -> VO，并设置 templateType
        Map<Long, AgCategoryVO> map = new HashMap<>();
        for (AgCategoryVO category : allCategories) {
            Long categoryId = category.getId(); // 确保 Long 类型
            category.setTemplateType(templateMap.get(categoryId)); // 设置 templateType
            if (category.getChildren() == null) {
                category.setChildren(new ArrayList<>()); // 初始化 children
            }
            map.put(categoryId, category);
        }

        // 4. 组装树结构
        List<AgCategoryVO> roots = new ArrayList<>();
        for (AgCategoryVO category : allCategories) {
            if (category.getParentId() == 0) {
                roots.add(category);
            } else {
                AgCategoryVO parent = map.get(category.getParentId().longValue());
                if (parent != null) {
                    parent.getChildren().add(category);
                }
            }
        }

        return roots;
    }

    private List<AgCategoryVO> convertToVO(List<AgCategoryEntity> categories) {
        List<AgCategoryVO> result = new ArrayList<>();
        for (AgCategoryEntity category : categories) {
            AgCategoryVO vo = new AgCategoryVO();
            BeanUtils.copyProperties(category, vo);
            result.add(vo);
        }
        return result;
    }


}
